/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Acceso;

import Modelo.DAL.Personal_DAO;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionErrors;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author glpc
 * @modified Rafael
 */
public class AutenticarUsuarioAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String FAILURE = "failure";
    private static final String SUCCESS = "success";
    private static final String CAMBIARPWD = "cambiarPassword";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession sesion = request.getSession(true); // Creamos la sesion
        AutenticarUsuarioForm formBean = (AutenticarUsuarioForm) form;
        ActionErrors errors = new ActionErrors();

        //Obteniendo los valores escritos en el formulario.
        String usuario = formBean.getUsuario();
        String password = formBean.getPassword();
        boolean hayError = false;

        if (usuario == null || usuario.length() < 1) {
            errors.add("usuario_requerido", new ActionMessage("errors.usuario_requerido"));
            saveErrors(request, errors);
            hayError = true;
        }
        if (password == null || password.length() < 1) {
            errors.add("password_requerido", new ActionMessage("errors.password_requerido"));
            saveErrors(request, errors);
            hayError = true;
        }
        if (hayError) {
            return mapping.findForward(FAILURE);
        }

        JSONObject user = Personal_DAO.AutenticarUsuario(usuario);
        System.out.println(user.toString());
        if ((user != null) && (user.has("pwd")) && (user.has("cedula"))) {
            String token = (String) sesion.getAttribute("token");
            String realPwd = user.getString("pwd");
            String realPwdHash = FormatUtility.md5(token + "" + realPwd);
            if (password.equals(realPwdHash)) {
                String cedula = user.getString("cedula").substring(2);
                if (realPwd.equals(FormatUtility.md5(cedula))) {
                    System.out.println("\n\n\nceudla 0 pwd");
                    return mapping.findForward(CAMBIARPWD);
                } else {
                    List rolList = new ArrayList<String>();
                    if (user.has("roles")) {
                        JSONArray roles = user.getJSONArray("roles");
                        for (int i = 0; i < roles.length(); i++) {
                            rolList.add(roles.getString(i));
                        }
                    }
                    sesion.invalidate();
                    sesion = null;
                    sesion = request.getSession();
                    sesion.setMaxInactiveInterval(60 * 30);
                    sesion.setAttribute("user", usuario);
                    sesion.setAttribute("nombre", user.getString("nombre"));
                    sesion.setAttribute("roles", rolList);

                    return mapping.findForward(SUCCESS);
                }
            }
        }
        errors.add("login_fallido", new ActionMessage("errors.login_fallido"));
        saveErrors(request, errors);
        return mapping.findForward(FAILURE);

    }
}
